//
//  HHWDependentPicker.swift
//  Pickers
//
//  Created by 鲁万财 on 15/7/27.
//  Copyright (c) 2015年 鲁万财. All rights reserved.
//

import UIKit

class HHWDependentPicker: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
    
    private var stateZips: NSDictionary!;
    private var states: Array<String>!;
    private var zips: Array<String>!;
    private let kStateComponent = 0;
    private let kZipComponent = 1;
    
    @IBOutlet weak var dependentPicker: UIPickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad();
        
        var bundle = NSBundle.mainBundle();
        var plistURL = bundle.URLForResource("statedictionary", withExtension: "plist");
        self.stateZips = NSDictionary(contentsOfURL: plistURL!);
        var allStates = self.stateZips.allKeys as NSArray;
        var sortedStates = allStates.sortedArrayUsingSelector(Selector("compare:"));
        self.states = sortedStates as! Array<String>;
        var selectedState = self.states[0];
        self.zips = self.stateZips[selectedState] as! Array<String>;
    }
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 2;
    }
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if(component == self.kStateComponent) {
            return self.states.count;
        } else {
            return self.zips.count;
        }
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        if(component == kStateComponent) {
            return self.states[row];
        } else {
            return self.zips[row];
        }
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if(component == kStateComponent) {
            var selectedStates = self.states[row];
            self.zips = self.stateZips[selectedStates] as! Array<String>;
            self.dependentPicker.reloadComponent(kZipComponent);
            self.dependentPicker.selectRow(0, inComponent: kZipComponent, animated: true)
        }
    }
}
